<template>
  <!-- 请假申请 -->
  <div class="leave-request">
    <van-cell
      :value="campus"
      is-link
      @click="campusPop = true"
      style="margin-bottom:12px;"
      v-if="roleType=='parent'"
    >
      <!-- 使用 title 插槽来自定义标题 -->
      <template slot="title">
        <span class="custom-title">学员姓名/校区</span>
        <span class="custom-title" style="color:red">*</span>
      </template>
    </van-cell>
    <van-cell :value="type" is-link @click="typePop = true">
      <!-- 使用 title 插槽来自定义标题 -->
      <template slot="title">
        <span class="custom-title">请假类型</span>
        <span class="custom-title" style="color:red">*</span>
      </template>
    </van-cell>
    <!-- 学员请假 -->
    <van-cell-group style="margin-top:12px;" v-if="roleType == 'parent'">
      <van-cell :value="sTime" is-link @click="stimePop = true" :clickable="true">
        <template slot="title">
          <span class="custom-title">开始时间</span>
          <span class="custom-title" style="color:red">*</span>
        </template>
      </van-cell>
      <van-cell :value="eTime" is-link @click="endTimeClick">
        <template slot="title">
          <span class="custom-title">结束时间</span>
          <span class="custom-title" style="color:red">*</span>
        </template>
      </van-cell>
      <van-cell>
        <template slot="title">
          <span class="custom-title">请假时长</span>
          <span class="custom-title" style="color:red">*</span>
        </template>
        <template slot="right-icon">
          <span>{{time}}</span>
          <span style="color:rgba(16, 16, 16, 0.45)">天</span>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 职工请假 --------------------------------------------------->
    <van-cell-group style="margin-top:12px;" v-if="roleType == 'teacher'">
      <van-cell :value="start|dateFilter" is-link @click="sTimePop = true">
        <template slot="title">
          <span class="custom-title">开始时间</span>
          <span class="custom-title" style="color:red">*</span>
        </template>
      </van-cell>
      <van-cell :value="end|dateFilter" is-link @click="eTimePop = true">
        <template slot="title">
          <span class="custom-title">结束时间</span>
          <span class="custom-title" style="color:red">*</span>
        </template>
      </van-cell>
      <van-cell>
        <template slot="title">
          <span class="custom-title">请假时长</span>
          <span class="custom-title" style="color:red">*</span>
        </template>
        <template slot="right-icon">
          <span>{{teacherTime|timeFilter}}</span>
          <span style="color:rgba(16, 16, 16, 0.45)">时</span>
        </template>
      </van-cell>
    </van-cell-group>
    <van-field
      style="margin-top:12px;"
      v-model="message"
      rows="4"
      autosize
      label="请假原因"
      type="textarea"
      maxlength="50"
      placeholder="请输入请假原因"
      show-word-limit
    />
    <van-field name="uploader" label="图片说明" style="margin-top:12px;">
      <template #input>
        <van-uploader v-model="uploader" max-count="1" :after-read="afterRead" accept="image/*" />
      </template>
    </van-field>
    <div class="column-center" style="position:fixed;bottom:64px;width:100%;border-radius:8px;">
      <van-button
        style="border-radius:8px;width:90%;"
        color="#6CC9D2"
        size="large"
        @click="onSubmit"
        :disabled="submitAble"
      >确认提交</van-button>
    </div>
    <!-- 弹窗--选择器 校区、类型、开始时间、结束时间、 -->
    <van-popup v-model="campusPop" position="bottom">
      <van-picker
        show-toolbar
        :columns="campusList"
        @confirm="campusConfirm"
        value-key="name"
        @cancel="campusPop = false"
      />
    </van-popup>
    <van-popup v-model="typePop" position="bottom">
      <van-picker
        show-toolbar
        :columns="typeList"
        @confirm="typeConfirm"
        value-key="types"
        @cancel="typePop = false"
      />
    </van-popup>
    <van-popup v-model="stimePop" position="bottom" class="flex-row">
      <van-datetime-picker
        v-model="sDate"
        type="date"
        :min-date="minDate"
        @change="stimeChange"
        style="width:75%"
        :show-toolbar="false"
      />
      <van-picker style="width:25%" :columns="columns" @change="sChange" />
    </van-popup>
    <van-popup v-model="etimePop" position="bottom" class="flex-row">
      <van-datetime-picker
        v-model="eDate"
        type="date"
        style="width:75%"
        :min-date="eMinDate"
        @change="eTimeChange"
        :show-toolbar="false"
      />
      <van-picker style="width:25%" :columns="ecolumns" @change="eChange" />
    </van-popup>
    <!-- 职工开始结束时间弹窗 -->
    <van-popup v-model="sTimePop" position="bottom">
      <van-datetime-picker
        v-model="sCurrentDate"
        type="datetime"
        :min-date="tsminDay"
        @confirm="tStartTime"
      />
    </van-popup>
    <van-popup v-model="eTimePop" position="bottom">
      <van-datetime-picker
        v-model="eCurrentDate"
        type="datetime"
        :min-date="teminDay"
        @confirm="tEndTime"
      />
    </van-popup>
  </div>
</template>

<script>
import { LeaveInfo, UpLoadImg } from "@/api/personal";
import { mapGetters } from "vuex";
import { Toast, CellGroup } from "vant";
import moment from "moment";
export default {
  data() {
    return {
      // --------------------------------------------------------家长端
      campus: "请选择",
      campusList: [],
      campusID: "", //家长所选校区
      studentName: "", //姓名
      type: "请选择", //类型
      typeList: [],
      columns: ["上午", "下午"],
      ecolumns: ["上午", "下午"],
      scolumn: "上午",
      ecolumn: "上午",
      message: "", //留言
      imgPath: "", //图片上传路径
      uploader: [],
      campusPop: false,
      typePop: false,
      stimePop: false,
      etimePop: false,
      minDate: new Date(),
      eMinDate: new Date(),
      sDate: null, //开始时间选择器初始值
      eDate: null, //结束时间选择器初始值
      sSelectTime: this.$moment().format("YYYY-MM-DD"), //页面展示开始选择时间
      eSelectTime: this.$moment().format("YYYY-MM-DD"), //页面展示结束选择时间
      submitAble: false,
      // -------------------------------------------------------职工端
      start: "请选择", //开始时间页面数据
      end: "请选择", //结束时间页面数据
      sTimePop: false, //职工开始时间弹窗
      sCurrentDate: new Date(), //职工开始时间
      eCurrentDate: new Date(), //职工结束时间
      eTimePop: false, //职工结束时间弹窗
      teacherTime: 0.0, //职工请假时长
      tsminDay: new Date(),
      teminDay: new Date()
    };
  },
  methods: {
    // 家长--弹窗选择时间事件
    stimeChange() {
      this.sSelectTime = this.$moment(this.sDate).format("YYYY-MM-DD");
      // 开始时间决定结束时间最小时间
      this.eMinDate = this.sDate;
    },
    // 家长--弹窗选择时间事件
    eTimeChange() {
      this.eSelectTime = this.$moment(this.eDate).format("YYYY-MM-DD");
    },
    // 请假类型选择
    typeConfirm(value) {
      this.type = value.types;
      this.typePop = false;
    },
    // 家长--校区选择
    campusConfirm(value) {
      this.studentName = value.studentName;
      this.campus = value.name;
      this.campusID = value.campusID;
      this.campusPop = false;
    },
    // 家长--弹窗选择时间事件
    sChange(picker, value, index) {
      this.scolumn = value;
    },
    // 家长--弹窗选择时间事件
    eChange(picker, value, index) {
      this.ecolumn = value;
    },
    //点击结束时间单元格
    endTimeClick() {
      if (this.sTime == "请选择") {
        Toast.fail("请选择开始时间");
      } else {
        if (!this.$moment(this.sDate).isSame(this.eDate)) {
          this.ecolumns = ["上午", "下午"];
          this.ecolumn = "上午";
        } else if (this.scolumn == "下午") {
          this.ecolumns = ["下午"];
          this.ecolumn = "下午";
        }
        this.etimePop = true;
      }
    },
    // 请假申请提交
    async onSubmit() {
      if (this.campusID == "" && this.roleType != "teacher") {
        Toast("请选择姓名/校区！");
      } else if (this.type == "请选择") {
        Toast("请选择请假类型！");
      } else if (this.sTime == "请选择" && this.roleType == "parent") {
        Toast("请选择开始时间！");
      } else if (this.eTime == "请选择" && this.roleType == "parent") {
        Toast("请选择结束时间！");
      } else if (this.roleType == "parent") {
        Toast.loading({
          forbidClick: true,
          duration: 0
        });
        //校验后发起请求
        const result = await LeaveInfo("get", {
          cmd: "apply_takeoff",
          phoneNumber: this.phone,
          role: this.roleType,
          types: this.type, //请假类型
          begin_time: this.sTime,
          end_time: this.eTime,
          takeoff_time: this.time,
          remark: this.message,
          picture_path: this.imgPath,
          campusID: this.campusID,
          studentName: this.studentName
        });
        if (result.result == "OK") {
          // result.data; //审批code
          Toast.success("提交成功！");
          setTimeout(() => {
            this.$router.replace({
              name: "LeaveDetail",
              params: { code: result.data }
            });
          }, 2000);
        } else if (result.code == "-10") {
          Toast.fail('学员已毕业！')
        } else {
          Toast.clear();
        }
      } else if (this.start == "请选择") {
        Toast("请选择开始时间！");
      } else if (this.end == "请选择") {
        Toast("请选择结束时间！");
      } else if (this.roleType == "teacher") {
        Toast.loading({
          forbidClick: true,
          duration: 0
        });
        //校验后发起请求
        const result = await LeaveInfo("get", {
          cmd: "apply_takeoff",
          phoneNumber: this.phone,
          role: this.roleType,
          types: this.type, //请假类型
          begin_time: this.start,
          end_time: this.end,
          takeoff_time: this.teacherTime,
          remark: this.message,
          picture_path: this.imgPath,
          campusID: this.tCampusID
        });
        if (result.result == "OK") {
          Toast.success("提交成功！");
          setTimeout(() => {
            this.$router.replace({
              name: "LeaveDetail",
              params: { code: result.data }
            });
          }, 2000);
        } else {
          Toast.fail("提交失败！");
        }
      }
    },
    // 图片上传
    async afterRead(file) {
      this.submitAble = true;
      if (file.file.size > 1048576) {
        let canvas = document.createElement("canvas"); // 创建Canvas对象(画布)
        let context = canvas.getContext("2d");
        let img = new Image();
        img.src = file.content; // 指定图片的DataURL(图片的base64编码数据)
        img.onload = async () => {
          canvas.width = 1000;
          canvas.height =750;
          context.drawImage(img, 0, 0, 1000, 750);
          file.content = canvas.toDataURL(file.file.type, 0.95); // 0.92为默认压缩质量
          let files = this.dataURLtoFile(file.content, file.file.name);
          console.log(files);
          
          let formData = new FormData();
          formData.append("imgStr", files);
          formData.append("phoneNumber", this.phone);
          formData.append("cmd", "upload_picture");
          const result = await UpLoadImg(formData);
          if (result.code == 200) {
            this.imgPath = result.data;
            file.url = result.data
            file.status = "done";
          } else {
            file.status = "failed";
            file.message = "上传失败";
            this.imgPath = "";
          }
        };
      } else {
        file.status = "uploading";
        file.message = "上传中...";
        let formData = new FormData();
        formData.append("imgStr", file.file);
        formData.append("phoneNumber", this.phone);
        formData.append("cmd", "upload_picture");
        const result = await UpLoadImg(formData);
        if (result.code == 200) {
          this.imgPath = result.data;
          file.url = result.data
          file.status = "done";
        } else {
          file.status = "failed";
          file.message = "上传失败";
          this.imgPath = "";
        }
      }
      this.submitAble = false;
    },
    dataURLtoFile(dataurl, filename) {
      // 将base64转换为file文件
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    // 日历选择
    tStartTime(value) {
      if (
        this.end != "请选择" &&
        this.$moment(value).isAfter(this.$moment(this.end))
      ) {
        this.end = "请选择";
      }
      this.start = value;
      this.sTimePop = false;
    },
    tEndTime(value) {
      if (this.$moment(this.start).isAfter(this.$moment(value))) {
        this.start = "请选择";
      }
      this.end = value;
      this.eTimePop = false;
    },
    // 计算教师请假时长
    async calculateTime(begin_time, end_time) {
      const result = await LeaveInfo("get", {
        cmd: "calculate_takeoff_time",
        phoneNumber: this.phone,
        role: this.roleType,
        campusID: this.tCampusID,
        begin_time: begin_time,
        end_time: end_time
      });
      console.log("result :", result);
      if (result.result == "OK") {
        this.teacherTime = parseFloat(result.data).toFixed(1);
      }
    }
  },
  async created() {
    Toast.loading({
      forbidClick: true,
      duration: 0
    });
    // 如果角色为家长则获取校区;
    if (this.roleType == "parent") {
      const result = await LeaveInfo("get", {
        cmd: "load_apply_campus",
        role: this.roleType,
        phoneNumber: this.phone
      });
      if (result.result == "OK") {
        result.data.forEach((item, index) => {
          this.campusList.push({
            campusID: item.campusID,
            name: item.studentName + "   " + item.campusName,
            campusName: item.campusName,
            studentName: item.studentName
          });
        });
      }
    }
    // 获取请假类型
    const res = await LeaveInfo("get", {
      cmd: "load_apply_types",
      role: this.roleType,
      phoneNumber: this.phone
    });
    if (res.result == "OK") {
      this.typeList = res.data;
    }
    Toast.clear();
  },
  computed: {
    ...mapGetters({
      phone: "getPhone",
      roleType: "getRoleType",
      tCampusID: "getCampusID"
    }),
    // 计算学员请假时长
    time() {
      let day = parseInt(
        this.$moment(this.eSelectTime).diff(
          this.$moment(this.sSelectTime),
          "day"
        )
      );
      if (this.sTime != "请选择" && this.eTime != "请选择") {
        if (this.scolumn == this.ecolumn) {
          //开始上午 结束上午
          if (day == 0) {
            return day + 0.5;
          } else if (day > 0) {
            return day + 0.5;
          } else {
            return -1;
          }
        } else if (this.scolumn == "上午" && this.ecolumn == "下午") {
          //开始上午 结束下午
          if (day == 0) {
            return 1;
          } else if (day > 0) {
            return day + 1;
          } else {
            return -1;
          }
        } else {
          //开始下午 结束上午
          if (day == 0) {
            return -1;
          } else if (day > 0) {
            return day;
          } else {
            return -1;
          }
        }
        return 1;
      }
      return 0;
    },
    sTime() {
      if (this.sDate == null) {
        return "请选择";
      }
      return this.sSelectTime + "  " + this.scolumn;
    },
    eTime() {
      if (this.eDate == null) {
        return "请选择";
      }
      return this.eSelectTime + "  " + this.ecolumn;
    }
  },
  watch: {
    sDate() {
      if (
        this.$moment(this.sDate).isAfter(this.eDate) &&
        !this.$moment(this.sDate).isSame(this.eDate)
      ) {
        this.eDate = this.sDate;
        this.eSelectTime = this.$moment(this.eDate).format("YYYY-MM-DD");
        this.eMinDate = this.sDate;
        if (this.scolumn == "下午") {
          this.ecolumns = ["下午"];
          this.ecolumn = "下午";
        }
      }
      //点击初始化
      if (this.eDate == null) {
        this.eMinDate = this.sDate;
        this.eSelectTime = this.$moment(this.sDate).format("YYYY-MM-DD");
      }
      // 当前时间是上午还是下午
      if (
        this.$moment(this.sDate).hour() > 12 &&
        this.$moment(this.sDate).format("YYYY-MM-DD") ==
          this.$moment(new Date()).format("YYYY-MM-DD")
      ) {
        this.columns = ["下午"];
        this.scolumn = "下午";
      } else {
        this.columns = ["上午", "下午"];
        this.scolumn = "上午";
      }
    },
    scolumn() {
      if (this.eDate == null && this.scolumn == "下午") {
        this.ecolumns = ["下午"];
        this.ecolumn = "下午";
      }
    },
    eDate() {
      if (!this.$moment(this.sDate).isSame(this.eDate)) {
        this.ecolumns = ["上午", "下午"];
        this.ecolumn = "上午";
      } else if (this.scolumn == "下午") {
        this.ecolumns = ["下午"];
        this.ecolumn = "下午";
      }
    },
    scolumn() {
      if (this.$moment(this.sDate).isSame(this.eDate) && value == "下午") {
        this.ecolumns = ["下午"];
        this.ecolumn = "下午";
      }
    },
    start() {
      if (this.start != "请选择" && this.end != "请选择") {
        this.calculateTime(
          this.$moment(this.start).format("YYYY-MM-DD HH:mm:ss"),
          this.$moment(this.end).format("YYYY-MM-DD HH:mm:ss")
        );
      }
    },
    end() {
      if (this.start != "请选择" && this.end != "请选择") {
        this.calculateTime(
          this.$moment(this.start)
            .set("second", "00")
            .format("YYYY-MM-DD HH:mm:ss"),
          this.$moment(this.end)
            .set("second", "00")
            .format("YYYY-MM-DD HH:mm:ss")
        );
      }
    }
  },
  filters: {
    dateFilter(value) {
      if (value == "请选择") {
        return value;
      } else {
        return moment(value).format("YYYY-MM-DD HH:mm");
      }
    },
    timeFilter(value){
      return parseFloat(value).toFixed(1)
    }
  }
};
</script>

<style lang="scss" scoped>
.leave-request {
  position: fixed;
  width: 100%;
  height: 100%;
  background-color: #f7f7f7;
}
.van-picker__columns {
  height: 350px !important;
}
</style>